<template>
  <div style='height: calc(100vh - 120px)'>
    <!--  -->
    <crumbs @goBack='() => {}' :superiorMenu="['报表统计']" currentMenu='实时库存表' style='margin-bottom: 12px'>
      <span slot='content'>
        <div class='topSearch'>
          <a-form-model ref='ruleForm' layout='inline' :model='filterForm'>
            <a-form-model-item label='物品编号'>
              <a-input @change='topSearch()' :placeholder="'请输入物品编号'" v-model="filterForm['serialNumber']" />
            </a-form-model-item>
            <a-form-model-item label='物品名称'>
              <a-input @change='topSearch()' :placeholder="'请输入物品名称'" v-model="filterForm['serialName']" />
            </a-form-model-item>
            <a-button @click='handleShowFilter' style='margin-top: 4px' icon='filter'
            >筛选 <span class='filter-num' style='margin-left: 5px'>{{ ' ' + filteredNums }}</span></a-button
            >
          </a-form-model>
        </div>
      </span>
    </crumbs>
    <!-- 头部模块 -->
    <a-card :bordered='false'>
      <div class='topBox'>
        <div class='itemBox' v-for='(item, index) in topArray' :key='index'>
          <div class='rightBox'>
            <div class='rightBot'>{{ item.title }}</div>
            <div class='rightTop'>{{ item.number }}</div>
          </div>
        </div>
      </div>
    </a-card>
    <div style='height: 12px; background: #f0f2f5'></div>

    <a-card :bordered='false' style='height: calc(100vh - 390px)'>
      <!-- 操作按钮区域 -->
      <div class='table-operator right-btn'>
        <a-button @click='showColumn' icon='unordered-list' style='margin-right: 10px'> 设置列</a-button>
        <a-button @click='handleExport(selectedRows)' icon='upload' style='float: right' class='btns' v-if="hasButton('realTimeInventory:derive')">导出</a-button>
      </div>
      <div>
        <a-table
          row-key='goodsId'
          size='middle'
          :key='tableKey'
          :scroll="{ x: scrollX, y: 'calc(100vh - 520px)' }"
          :hideDefaultSelections='false'
          :columns='columns'
          :dataSource='modelList'
          :pagination='false'
          @change='tableChange'
          :row-selection="{ selectedRowKeys: selectedRowKeys, columnTitle: ' ', onChange: onSelectChange }"
          class='j-table-force-nowrap'
          :components="drag(columns, 'BUDGET_REPORT')"
        >
          <span slot='category' slot-scope='text, record'>{{ record.categoryText || '-' }} </span>
          <!-- 6个字符控制 超出。。。 -->
          <span :title='text' slot='serialName' slot-scope='text'>
            {{ text }}
          </span>
          <span :title='text' slot='categoryText' slot-scope='text'>
            {{ text }}
          </span>
          <!-- 行信息 -->
          <span
            slot='serialNumber'
            :title='record.serialNumber'
            slot-scope='text, record'
            class='btn-text'
            @click='handleDetail(record)'
          >
            {{ record.serialNumber || '-' }}
          </span>
          <span slot='reporter' :title='record.reporterText' slot-scope='text, record'>{{ record.reporterText }}</span>

          <span slot='amount' :title='commafyTofixed(record.amount, 2)' slot-scope='text, record'>{{
              commafyTofixed(record.amount, 2)
            }}</span>
          <span slot='payAmount' :title='commafyTofixed(record.payAmount, 2)' slot-scope='text, record'>{{
              commafyTofixed(record.payAmount, 2)
            }}</span>
          <span slot='unPayAmount' :title='commafyTofixed(record.unPayAmount, 2)' slot-scope='text, record'>{{
              commafyTofixed(record.unPayAmount, 2)
            }}</span>
          <span
            slot='programStatusText'
            :title='text'
            slot-scope='text, record'
            :style='{ color: taskStatusCheck(record.programStatus) }'
          >{{ text }}</span
          >

          <!-- 输入框搜索 -->
          <div slot='searchInput' slot-scope='{ selectedKeys, confirm, clearFilters, column }' class='searchWorkOreder'>
            <a-input
              placeholder='请输入'
              v-model='filterForm[column.dataIndex]'
              style='width: 188px; display: block'
              @pressEnter='handleSearch'
            />
            <a-button
              type='primary'
              style='width: 80px; margin-left: 20px; display: block'
              @click='() => handleSearch(selectedKeys, confirm, column.dataIndex, clearFilters)'
            >
              搜索
            </a-button>
          </div>
          <a-icon
            slot='searchIcon'
            slot-scope='filtered'
            type='search'
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
          <!-- 选择搜索 -->
          <div slot='selectDropdown' slot-scope='{ confirm, clearFilters, column }' class='searchWorkOreder'>
            <a-tree-select
              v-if="column.dataIndex == 'category'"
              allow-clear
              v-model='filterForm[selectkeys(column.dataIndex)]'
              :multiple='false'
              placeholder='请选择'
              style='width: 200px'
              :tree-data='treeData'
              :replaceFields='replaceFields'
              :show-checked-strategy='SHOW_PARENT'
              search-placeholder='请选择'
              @change='treeChange'
            />
            <a-select
              mode='multiple'
              placeholder='请选择'
              style='width: 200px'
              v-model='filterForm.serialPropertiesName'
              v-if="column.dataIndex == 'serialPropertiesName'"
              @change='(v) => changeSelect(v, column.dataIndex)'
            >
              <a-select-option v-for='item in serialPropertiesNameList' :key='item.value' :value='item.value'>
                {{ item.label }}
              </a-select-option>
            </a-select>
            <a-button
              type='primary'
              style='width: 80px; margin-left: 20px; display: block'
              @click='() => handleSearch(confirm, column.dataIndex, clearFilters)'
            >
              搜索
            </a-button>
          </div>
          <!-- 选择搜索 -->
          <div slot='selectDropdownSingle' slot-scope='{ confirm, clearFilters, column }' class='searchWorkOreder'>
            <a-select
              placeholder='请选择'
              allowClear
              style='width: 188px'
              v-model='filterForm[selectkeys(column.dataIndex)]'
              @change='(v) => changeSelect(v, selectkeys(column.dataIndex))'
            >
              <a-select-option
                v-for='(item, i) in selectOptions(column.dataIndex)'
                :key='i'
                :value='item[column.selectValue]'
              >{{ item[column.selectText] }}
              </a-select-option
              >
            </a-select>
            <a-button
              type='primary'
              style='width: 80px; margin-left: 20px; display: block'
              @click='() => handleSearch(confirm, column.dataIndex, clearFilters)'
            >
              搜索
            </a-button>
          </div>
          <a-icon
            slot='selectIcon'
            slot-scope='filtered'
            type='filter'
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
          <!-- 日期搜索 -->
          <div slot='datePicker' slot-scope='{ confirm, clearFilters, column }' class='searchWorkOreder'>
            <a-range-picker
              style='width: 188px'
              v-model='dateForm[column.dataIndex]'
              format='YYYY-MM-DD'
              :placeholder="['开始时间', '结束时间']"
              @change='(v) => onOk(v, column.dataIndex)'
            />
            <a-button
              type='primary'
              style='width: 80px; margin-left: 20px; display: block'
              @click='() => handleSearch(confirm, column.dataIndex, clearFilters)'
            >
              搜索
            </a-button>
          </div>
          <a-icon
            slot='dateIcon'
            slot-scope='filtered'
            type='filter'
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
        </a-table>
      </div>
      <SetColumn
        columnName='设置列'
        ref='SetColumn'
        v-if='showSetColumn'
        @sureBtn='sureBtn'
        @cancelBtn='showSetColumn = false'
      />
    </a-card>
    <a-drawer placement='right' width='500' :visible='showFilter' @close='closeFilter'>
      <div class='filter-body'>
        <div slot='title' class='uni-card filter-tit'>
          筛选 <span class='filter-num'>{{ filteredNums }}</span>
        </div>
        <div class='uni-card' v-if='filteredNums > 0' style='background: #fff'>
          <div v-for='(item, i) in filteredList' :key='i' v-show='item.text' class='tag-wrap'>
            <span class='filter-tag' @click='delFiltered(item.key)'>
              <span class='tag-text'>{{ `${item.title}：${item.text}` }}</span>
              <a-icon type='close' style='float: right' />
            </span>
          </div>
        </div>
        <div style='overflow-y: scroll; flex: 1; padding: 0'>
          <div class='uni-card' style='background: #fff'>
            <a-form-model ref='ruleForm' layout='vertical' :model='filterForm'>
              <a-form-model-item label='物品编号'>
                <a-input v-model='filterForm.serialNumber' placeholder='请输入' />
              </a-form-model-item>
              <a-form-model-item label='物品名称'>
                <a-input v-model='filterForm.serialName' placeholder='请输入' />
              </a-form-model-item>
              <a-form-model-item label='规格'>
                <a-input v-model='filterForm.serialSpecifications' placeholder='请输入' />
              </a-form-model-item>
              <a-form-model-item label='物品属性'>
                <a-select mode='multiple' placeholder='请选择' v-model='filterForm.serialPropertiesName'>
                  <a-select-option v-for='item in serialPropertiesNameList' :key='item.value' :value='item.value'>
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label='创建日期'>
                <a-range-picker
                  :allowClear='true'
                  v-model="dateForm['createTime']"
                  style='width: 100%'
                  :disabled-date='disabledStartDate'
                  @change="(v) => onOk(v, 'createTime')"
                />
              </a-form-model-item>
              <!-- <a-form-model-item label="分类">
                <a-tree-select
                  allow-clear
                  v-model="filterForm.category"
                  :multiple="false"
                  placeholder="请选择"
                  style="width: 100%"
                  :tree-data="treeData"
                  :replaceFields="replaceFields"
                  :show-checked-strategy="SHOW_PARENT"
                  search-placeholder="请选择"
                  @change="treeChange"
                />
              </a-form-model-item> -->
              <!-- <a-form-model-item label="类型">
                <a-select
                  mode="multiple"
                  placeholder="请选择"
                  allowClear
                  style="width: 100%"
                  v-model="filterForm['type']"
                  @change="(v) => changeSelect(v, 'type')"
                >
                  <a-select-option v-for="option in typeList" :key="option.value" :value="option.value">{{
                    option.title
                  }}</a-select-option>
                </a-select>
              </a-form-model-item> -->
            </a-form-model>
          </div>
        </div>
        <div class='footer-submit'>
          <a-button class='margin-btn' @click='resetFilter'>重置</a-button>
          <a-button type='primary' @click='handleFilter'>确定</a-button>
        </div>
      </div>
    </a-drawer>
    <!-- 全选/分页 -->
    <div class='uni-card pagination-contian' :style="{ left: collapsed ? '199px' : '70px' }">
      <div style='display: inline-block' :style="{ marginLeft: collapsed ? '33px' : '45px' }">
        <a-checkbox :indeterminate='listIndeterminate' :checked='listCheckAll' @change='onCheckAllChange'></a-checkbox>
        <span style='margin-left: 8px'>
          {{ `已选 ${selectedRowKeys.length}/${total} 项` }}
          <span @click='clearArr' class='pubColor' style='margin: 0 10px'>清空</span>
        </span>
      </div>
      <div style='display: inline-block; float: right'>
        <a-pagination
          :total='total'
          v-model='current'
          :page-size-options='pageSizeOptions'
          :page-size='pageSize'
          @change='onChangePage'
          @showSizeChange='onShowSizeChange'
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
    <a-modal style='width: 50%' v-model='selectExportVisiable' title='导出'>
      <template slot='footer'>
        <a-button key='back' @click='handleExportAll'> 导出全部数据</a-button>
        <a-button key='submit' type='primary' @click='handleSelectExport'> 导出选中数据</a-button>
      </template>
      {{ selectExportTitle }}
    </a-modal>
    <goodsManagementDetail ref='goodsManagementDetail'></goodsManagementDetail>
  </div>
</template>
<script>
import SetColumn from '@/pubComponent/SetColumn.vue'
import crumbs from '@/components/crumbs.vue'
import { getNewColumns, subStrText, commafyTofixed, formatDate } from '@/utils/util'
import { API } from '@/api/requestFzs'
import { APILX } from '@/api/requestLx'
import moment from 'dayjs'
import { httpAction, getAction, deleteAction, downFile, downFilePost } from '@/api/manage'
import { mapState } from 'vuex'
import { TreeSelect } from 'ant-design-vue'
import { ajaxGetDictItems, getEnableOne } from '@/api/api'
import { goodsList, categoryGetTree, getDictModel } from '@/api/goodsManagement'
import tableDragResize from '@/mixins/tableDragResize'
import { hasButton } from '@/utils/hasPermission'

const SHOW_PARENT = TreeSelect.SHOW_PARENT
const treeData = []
// 表头
const columnsValue = [
  {
    title: '物品编号',
    width: 180,
    ellipsis: true,
    dataIndex: 'serialNumber',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialNumber'
    }
  },
  {
    title: '物品名称',
    width: 150,
    ellipsis: true,
    dataIndex: 'serialName',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialName'
    }
  },
  {
    title: '规格',
    dataIndex: 'serialSpecifications',
    width: 150,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialSpecifications'
    }
  },
  {
    title: '物品属性',
    dataIndex: 'serialPropertiesName',
    ellipsis: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'serialPropertiesName'
    }
  },
  {
    title: '单位',
    dataIndex: 'unitName',
    width: 150,
    ellipsis: true,
    scopedSlots: {
      customRender: 'unitName'
    }
  },
  {
    title: '库存数量',
    width: 150,
    sorter: true,
    dataIndex: 'inventoryNum',
    scopedSlots: {
      customRender: 'inventoryNum'
    }
  }
  // {
  //   title: '分类',
  //   dataIndex: 'category',
  //   ellipsis: true,
  //   width: 150,
  //   scopedSlots: {
  //     filterDropdown: 'selectDropdown',
  //     filterIcon: 'selectIcon',
  //     customRender: 'category',
  //   },
  // },
  // {
  //   title: '类型',
  //   width: 150,
  //   ellipsis: true,
  //   dataIndex: 'typeText',
  //   selectValue: 'value',
  //   selectText: 'text',
  //   scopedSlots: {
  //     filterDropdown: 'selectDropdownSingle',
  //     filterIcon: 'selectIcon',
  //     customRender: 'typeText',
  //   },
  // },
]
// const actionArr = [
//   {
//     fixed: 'right',
//     title: '操作',
//     width: 50,
//     dataIndex: 'actions',
//     ellipsis: true,
//     scopedSlots: { customRender: 'actions' },
//   },
// ]
let startDate = moment().startOf('month').format('YYYY-MM-DD HH:mm:ss')
let endDate = moment().format('YYYY-MM-DD HH:mm:ss')
export default {
  name: 'realTimeInventoryProduction',
  mixins: [tableDragResize],
  data() {
    return {
      selectExportTitle: '',
      selectExportVisiable: false, // 导出弹窗
      selectExportParam: {}, // 导出参数
      filedKeys: '', // 导出字段
      fileName: '', // 导出文件名
      // 树
      treeData,
      SHOW_PARENT,
      treeSelectLael: '',
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
        value: 'id'
      },
      // 头部按月搜索
      monthEnd: '',
      monthStart: '',
      now: null,
      // 头部配置
      topArray: [
        {
          title: '物品种类',
          number: '0'
        },
        {
          title: '物品总数',
          number: '0'
        }
      ],

      typeList: [], //类型 字典值下拉数据
      dictOptionsDeviceCategory: [], //设备类别字典值下拉数据
      commafyTofixed,
      moment,
      selectedRowKeys: [],
      selectedRows: [],
      subStrText,
      showFilter: false, // 筛选抽屉
      modelList: [], // 列表数据
      showSetColumn: false, // 显示
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      current: 1,
      total: 0,
      pageSize: 30,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      columnsValue,
      columns: [
        {
          title: '物品编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'serialNumber',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'serialNumber'
          }
        },
        {
          title: '物品名称',
          width: 150,
          ellipsis: true,
          dataIndex: 'serialName',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'serialName'
          }
        },
        {
          title: '规格',
          dataIndex: 'serialSpecifications',
          width: 150,
          ellipsis: true,
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'serialSpecifications'
          }
        },
        {
          title: '物品属性',
          dataIndex: 'serialPropertiesName',
          ellipsis: true,
          width: 150,
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'serialPropertiesName'
          }
        },
        {
          title: '单位',
          dataIndex: 'unitName',
          width: 150,
          ellipsis: true,
          scopedSlots: {
            customRender: 'unitName'
          }
        },
        {
          title: '库存数量',
          width: 150,
          sorter: true,
          dataIndex: 'inventoryNum',
          scopedSlots: {
            customRender: 'inventoryNum'
          }
        }
        // {
        //   title: '分类',
        //   dataIndex: 'category',
        //   ellipsis: true,
        //   width: 150,
        //   scopedSlots: {
        //     filterDropdown: 'selectDropdown',
        //     filterIcon: 'selectIcon',
        //     customRender: 'category',
        //   },
        // },
        // {
        //   title: '类型',
        //   width: 150,
        //   ellipsis: true,
        //   dataIndex: 'typeText',
        //   selectValue: 'value',
        //   selectText: 'text',
        //   scopedSlots: {
        //     filterDropdown: 'selectDropdownSingle',
        //     filterIcon: 'selectIcon',
        //     customRender: 'typeText',
        //   },
        // },
      ],
      filterForm: {
        serialNumber: '',
        serialName: '',
        serialSpecifications: '',
        serialPropertiesName: undefined,
        createTime: '',
        timeBegin: startDate,
        timeEnd: endDate
        // category: [], //分类
        // type: [], //类型
      },
      filteredFormLable: {
        serialNumber: '物品编号',
        serialName: '物品名称',
        serialSpecifications: '规格',
        serialPropertiesName: '物品属性',
        createTime: '创建时间'
        // category: '分类',
        // type: '类型',
      },
      sortForm: {
        sortType: '',
        sortColumn: ''
      },
      dateForm: {
        createTime: [startDate, endDate]
      } /* 筛选日期绑定对象 */,
      customSelectList: [],
      applyStatusList: [],
      dealStatusList: [],
      serialPropertiesNameList: [
        { label: '自制', value: '0' },
        { label: '外购', value: '1' }
      ],
      loginUser: '',
      tableKey: 1.9
    }
  },
  components: {
    SetColumn,
    crumbs,
    goodsManagementDetail: (resolve) => require(['@/views/baseManagement/goodsManagement/detail'], resolve)
  },
  computed: {
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
    ...mapState({
      collapsed: (state) => state.user.collapsedAno
    }),
    filteredList() {
      let list = []
      for (let key in this.filterForm) {
        if (this.filteredFormLable[key] == '类型') {
          console.log('类型', this.typeList)
          let strArr = ''
          for (let item of this.filterForm[key]) {
            for (let each of this.typeList) {
              if (item == each.value) {
                strArr += each.title + '，'
              }
            }
          }
          strArr = strArr.substring(0, strArr.length - 1)
          list.push({
            title: this.filteredFormLable[key],
            text: strArr,
            key
          })
        } else if (this.filteredFormLable[key] == '分类' && key == 'category') {
          console.log('分类')
          list.push({
            title: this.filteredFormLable[key],
            text: this.treeSelectLael,
            key
          })
        } else if (key == 'reporter') {
          list.push({
            title: this.filteredFormLable[key],
            text: this.userNames,
            key
          })
        } else if (key == 'timeBegin' || key == 'timeEnd') {
          // 什么都不干
        } else if (key == 'createTime') {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm.timeBegin
              ? moment(this.filterForm.timeBegin).format('YYYY-MM-DD') +
              '-' +
              moment(this.filterForm.timeEnd).format('YYYY-MM-DD')
              : '',
            key
          })
        } else if (key == 'serialPropertiesName' && this.filterForm[key]) {
          list.push({
            title: this.filteredFormLable[key],
            text: this.statusToTxt(key, this.filterForm[key]),
            key
          })
        } else {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm[key],
            key
          })
        }
      }
      return list
    },
    filteredNums() {
      let nums = 0
      for (let key in this.filterForm) {
        if (this.filterForm[key] != '' && this.filterForm[key] != null && this.filterForm[key] != undefined) {
          nums += 1
          if (key == 'timeBegin') {
            nums -= 1
          }
        }
      }
      return nums
    }
  },
  created() {
    let user = localStorage.getItem('pro__Login_Userinfo')
    this.loginUser = JSON.parse(user).value.id
    // this.initData()
    this.requestData()
  },
  methods: {
    hasButton,
    topSearch() {
      this.handleSearch()
    },
    treeChange(value, label, extra) {
      console.log('label', value, label, extra)
      this.treeSelectLael = label[0]
    },
    // 限制开始日期
    disabledStartDate(current) {
      let nowMon = new Date()
      if (moment(nowMon).isBefore(moment(current))) {
        return true
      }
      return false
    },
    // 导出
    handleExport(e) {
      let that = this
      // 获取动态列
      let filedKeysList = []
      that.columns.forEach((item) => {
        if (item.dataIndex == 'category') {
          item.dataIndex = 'categoryText'
        }
        filedKeysList.push(item.dataIndex)
      })
      // filedKeysList.pop()//删除最后一个的操作列
      that.filedKeys = filedKeysList.join(',')
      //设置文件名
      if (that.filterForm.timeBegin) {
        that.fileName = `${formatDate(that.filterForm.timeBegin, 'YYYY-MM-DD')}~${formatDate(
          that.filterForm.timeEnd,
          'YYYY-MM-DD'
        )} 实时库存表`
      } else {
        that.fileName = '实时库存表'
      }
      if (!e || e.length === 0) {
        that.handleExportAll()
        that.selectExportVisiable = false
      } else {
        that.selectExportTitle = `已选中${e.length}条数据`
        that.selectExportVisiable = true
        that.selectExportParam = {
          selectedList: e,
          fileName: that.fileName, //文件名
          filedKeys: that.filedKeys //动态列
        }
      }
    },
    handleSelectExport() {
      this.selectExportVisiable = false
      downFilePost('/inventory/inventory/exportInventoryXls', this.selectExportParam).then((data) => {
        if (data.type == 'application/json') {
          const reader = new FileReader() //创建一个FileReader实例
          reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
          reader.onload = function() {
            //读取完成后,**获取reader.result**
            const msg = JSON.parse(reader.result)
            this.$antdMessage.error(msg.message) //弹出错误提示
          }
          return
        }
        if (!data) {
          this.$antdMessage.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), this.fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', this.fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleExportAll() {
      let that = this
      that.selectExportVisiable = false
      that.$antdConfirm({
        title: `导出`,
        content: `确定全部数据?`,
        onOk() {
          let param = {
            ...that.filterForm,
            ...that.sortForm,
            createTimeBegin:that.filterForm.timeBegin,
            createTimeEnd:that.filterForm.timeEnd,
            fileName: that.fileName,
            filedKeys: that.filedKeys
          }
          delete param.timeBegin
          delete param.timeEnd
          // 删除param中的空子段
          for (let key in param) {
            if (param[key] == '' || param[key] == null || param[key] == undefined || param[key] == []) {
              delete param[key]
            }
          }
          console.log(param, '导出选中数据param')
          downFilePost('/inventory/inventory/exportInventoryXls', param).then((data) => {
            if (data.type == 'application/json') {
              const reader = new FileReader() //创建一个FileReader实例
              reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
              reader.onload = function() {
                //读取完成后,**获取reader.result**
                const msg = JSON.parse(reader.result)
                that.$antdMessage.error(msg.message) //弹出错误提示
              }
              return
            }
            if (!data) {
              that.$antdMessage.warning('文件下载失败')
              that.selectExportVisiable = false
              return
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(new Blob([data]), that.fileName + '.xls')
              that.selectExportVisiable = false
            } else {
              let url = window.URL.createObjectURL(new Blob([data]))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', that.fileName + '.xls')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link) //下载完成移除元素
              window.URL.revokeObjectURL(url) //释放掉blob对象
              that.selectExportVisiable = false
            }
          })
        },
        onCancel() {
        }
      })
    },

    changeSelect(v, key) {
      if (v.length == 0 || v == '' || v == undefined) {
        // this.filterForm[key] = undefined
        this.filterForm[key] = []
      }
    },
    selectkeys(key) {
      if (key == 'typeText') {
        return 'type'
      } else if (key == 'category') {
        return 'category'
      }
    },
    selectOptions(key) {
      if (key == 'deviceCategoryText') {
        return this.dictOptionsDeviceCategory
      } else if (key == 'flowStatusText') {
        return this.applyStatusList
      } else if (key == 'typeText') {
        return this.typeList
      }
    },
    /* 筛选类型回显文字 */
    statusToTxt(key, val) {
      var valList = []
      if (key == 'serialPropertiesName' && this.filterForm[key]) {
        for (let i = 0; i < val.length; i++) {
          const item = val[i]
          for (let j = 0; j < this.serialPropertiesNameList.length; j++) {
            const txt = this.serialPropertiesNameList[j]
            if (item == txt.value) {
              valList.push(txt.label)
            }
          }
        }
        return valList.join(',')
      } else if (key == 'deviceCategory' && this.filterForm[key]) {
        for (let i = 0; i < val.length; i++) {
          const item = val[i]
          for (let j = 0; j < this.dictOptionsDeviceCategory.length; j++) {
            const txt = this.dictOptionsDeviceCategory[j]
            if (item == txt.value) {
              valList.push(txt.title)
            }
          }
        }
        return valList.join(',')
      }
    },
    /* 类型颜色 */
    taskStatusCheck(v) {
      let checked = false
      if (v == '0') {
        checked = false
      } else if (v == '1') {
        checked = true
      }
      return checked ? '#ff943e' : '#00b042'
    },
    /* 出入库日期选择 */
    onOk(value, key) {
      if (value.length == 0) {
        this.filterForm.timeBegin = ''
        this.filterForm.timeEnd = ''
        this.filterForm[key] = ''
        return
      }
      this.filterForm.timeBegin = moment(value[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.filterForm.timeEnd = moment(value[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.handleSearch()
    },
    /* 创建时间选择 */
    onOkCreate(value, key) {
      if (value.length == 0) {
        this.filterForm[`createTimeStart`] = ''
        this.filterForm[`createTimeEnd`] = ''
        this.filterForm[key] = ''
        return
      }
      this.filterForm[`createTimeStart`] = moment(value[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.filterForm[`createTimeEnd`] = moment(value[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    },
    // 排序
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      console.log('看看这是啥33：', sorter)
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: sorter.columnKey == 'inventoryNum' ? 'inventory_num' : sorter.columnKey
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: ''
        }
        this.requestData()
      }
    },
    // table选择
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.checkBoxStatus()
    },
    // 全选
    // onCheckAllChange(e) {
    //   if (e.target.checked) {
    //     for (let item of this.modelList) {
    //       this.selectedRowKeys.push(item.goodsId)
    //     }
    //   } else {
    //     for (let item of this.modelList) {
    //       this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
    //         return each != item.goodsId
    //       })
    //     }
    //   }
    //   this.checkBoxStatus()
    // },
    // 全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.goodsId
          })
          this.selectedRowKeys.push(item.goodsId)
          this.selectedRows = this.selectedRows.filter((each) => {
            return each.goodsId != item.goodsId
          })
          this.selectedRows.push(item)
        }
      } else {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.goodsId
          })
          this.selectedRows = this.selectedRows.filter((each) => {
            return each.goodsId != item.goodsId
          })
        }
      }
      this.checkBoxStatus()
    },
    // 清空
    clearArr() {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.modelList) {
          tableIds.push(item.goodsId)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    onShowSizeChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    handleSearch(selectedKeys, confirm, dataIndex, clearFilters) {
      this.current = 1
      this.requestData()
    },
    /* 打开筛选 */
    handleShowFilter() {
      this.showFilter = true
    },
    /* 关闭筛选 */
    closeFilter() {
      this.showFilter = false
    },
    /* 确定筛选 */
    handleFilter() {
      this.handleSearch()
      this.showFilter = false
    },
    /* 删除已选 */
    delFiltered(key) {
      if (key == 'serialNumber') {
        this.filterForm[key] = ''
        this.handleSearch()
      } else if (this.filteredFormLable[key] == '创建时间') {
        this.filterForm.timeBegin = ''
        this.filterForm.timeEnd = ''
        this.filterForm[key] = ''
        this.dateForm[key] = null
      } else if (this.filteredFormLable[key] == '物品名称') {
        this.filterForm[key] = ''
        this.handleSearch()
      } else if (this.filteredFormLable[key] == '分类') {
        this.filterForm[key] = []
        this.treeSelectLael = ''
      } else if (this.filteredFormLable[key] == '类型') {
        this.filterForm[key] = []
      } else if (key == 'programStatus' || key == 'deviceCategory') {
        this.filterForm[key] = undefined
      } else {
        this.filterForm[key] = ''
      }
    },
    /* 重置筛选 */
    resetFilter() {
      this.filterForm = {
        serialNumber: '',
        serialName: '',
        serialSpecifications: '',
        serialPropertiesName: undefined,
        createTime: '',
        timeBegin: '',
        timeEnd: ''
      }
      this.dateForm = {
        createTime: ''
      }
      ;(this.treeSelectLael = ''), this.handleSearch()
    },
    /* 初始/加载设置列 */
    initData() {
      var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.BUDGET_REPORT)
      this.columns = getNewColumns(this.columnsValue, JSON.parse(oldValue), [], this.columns)
      /* 客户下拉 */
      API.erpCustomerList({ pageSize: 999, pageNo: 1 }).then((res) => {
        if (res.code == 200) {
          this.customSelectList = res.result.records
        }
      })
      ajaxGetDictItems('erp_apply_status').then((res) => {
        if (res.result) {
          this.applyStatusList = res.result
        }
      })
      ajaxGetDictItems('erp_contract_status').then((res) => {
        if (res.result) {
          this.dealStatusList = res.result
        }
      })
      // 字典接口
      getDictModel({ dictCode: 'mess_device_category' }).then((res) => {
        this.dictOptionsDeviceCategory = res.result
      })
      // 字典接口 类型
      getDictModel({ dictCode: 'wms_goods_type' }).then((res) => {
        this.typeList = res.result
      })
      // this.getTreeData()
    },
    // getTreeData() {
    //   // 取分类树
    //   categoryGetTree({ code: 'B05' }).then((res) => {
    //     let arr = res.result
    //     arr.map((item) => {
    //       if (item.children.length > 0) {
    //         item.disabled = true
    //         ;(function bianli(e = item) {
    //           e.children.forEach((item) => {
    //             if (item.children.length > 0) {
    //               item.disabled = true
    //               bianli(item)
    //             }
    //           })
    //         })()
    //       }
    //     })
    //     this.treeData = arr
    //   })
    // },
    /* 请求列表数据 */
    requestData(check) {
      let parameter = {
        pageNo: this.current,
        pageSize: this.pageSize,
        createTimeBegin: this.filterForm.timeBegin,
        createTimeEnd: this.filterForm.timeEnd
          ? moment(this.filterForm.timeEnd).format('YYYY-MM-DD') + ' ' + '23:59:59'
          : '',
        ...this.filterForm,
        ...this.sortForm
      }
      if (parameter.deviceCategory) {
        parameter.deviceCategory = parameter.deviceCategory.join(',')
      }
      if (parameter.type) {
        parameter.type = parameter.type.join(',')
      }
      if (parameter.serialPropertiesName) {
        parameter.serialProperties = parameter.serialPropertiesName.join(',')
      }
      delete parameter.createTime
      delete parameter.timeBegin
      delete parameter.timeEnd
      delete parameter.serialPropertiesName
      console.log('22222', parameter)
      this.initDataTop(parameter)
      APILX.getInventoryList(parameter).then((res) => {
        if (res.code == 200) {
          if (res.result.total) {
            this.total = res.result.total
          } else {
            this.total = 0
          }
          this.modelList = res.result.records
          if (check) {
            this.checkBoxStatus()
          }
        }
      })
    },
    initDataTop(parameter) {
      APILX.getInventoryStatistics(parameter).then(res => {
        if (res.code == 200) {
          if (res.result) {
            this.topArray[0].number = (res.result.goodsNum * 1).toLocaleString() || '0'
            this.topArray[1].number = (res.result.inventoryNum * 1).toLocaleString() || '0'
          }
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    /* 打开设置列面板 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(this.columnsValue, this.BUSI_CONST.Entity.BUDGET_REPORT, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      this.columns = getNewColumns(this.columnsValue, emitArr, [])
      console.log(this.columns)
      localStorage.setItem(this.BUSI_CONST.Entity.BUDGET_REPORT, JSON.stringify(emitArr))
      this.tableKey += 1
    },
    /* 详情 */
    handleDetail(v) {
      this.$refs.goodsManagementDetail.initDetail(v.serialInfoId)
      // this.$openWay(this, true, '/warehouseManagement/goodsManagement/goodsManagementDetail', { id: v.goodsId,backPath:'realTimeInventory' })
    },
    //点击返回按钮
    goBack() {
      console.log('goback')
    }
  }
}
</script>
<style scoped lang='less'>
@import '~@/assets/less/public.less';
// @import '~@assets/less/common.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}

.header {
  width: 150%;
  margin: -12px -12px @distance4;
}

.backBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .backC {
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}

.j-table-force-nowrap {
  margin-top: @distance1;
}

.btns {
  margin-left: @distance5;
}

.right-btn {
  // float: right;
  // display: flex;
  // justify-content: flex-end;
}

.mg-left {
  margin-left: @distance3;
}

.filter-tit {
  background: #fff;
  border-bottom: 1px solid @greyBorder;
  font-size: @fontSize4;
}

.filter-num {
  color: @normalFont;
}

.filter-body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.margin-btn {
  margin-right: @distance5;
}

.filter-tag {
  display: inline-block;
  position: relative;
  padding: 8px 10px;
  border-radius: 4px;
  font-size: @fontSize1;
  line-height: @fontSize1;
  max-width: 100%;
  background: @greyBg;
  color: @titFont;
  cursor: pointer;

  .tag-text {
    display: inline-block;
    padding-right: 20px;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .anticon-close {
    position: absolute;
    right: 8px;
    top: 8px;
  }
}

.tag-wrap:nth-of-type(n + 2) {
  margin-top: 10px;
}

.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}

/deep/ .ant-card-body {
  // height: calc(100vh - 214px);
  // overflow: hidden;
  padding: 20px 16px;
}

.pubColor {
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
}

div.topBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // margin-bottom: 16px;
  box-sizing: border-box;
  padding: 23px 0;
  background: #fff;

  div.itemBox {
    display: flex;
    justify-content: center;
    align-items: center;
    flex: 1;
    box-sizing: border-box;
    height: 44px;
    padding: 0px 60px;
    position: relative;
    border-right: 1px solid #eeeeee;

    div.rightBox {
      text-align: center;
      height: 44px;
      cursor: pointer;
      display: flex;
      align-items: flex-start;
      flex-direction: column;
      justify-content: flex-start;
      margin-left: 16px;

      div.rightTop {
        font-size: 24px;
        color: #191f25;
        line-height: 24px;
        margin-top: 12px;
      }

      div.rightBot {
        font-size: 14px;
        color: #888888;
      }
    }
  }
}

.topBox .itemBox:last-child {
  border: none;
}

.topSearch {
  padding: 0 0 10px 38px;
}

.table-operator .ant-btn {
  margin: 0 8px -4px 0;
}

/deep/ .ant-modal-footer {
  .ant-btn {
    width: 116px;
  }
}
</style>
